package imserver.service.impl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;

import imserver.beans.MemberInfo;
import imserver.common.util.DaoException;
import imserver.common.util.GernateNum;
import imserver.constant.LoginStatus;
import imserver.dao.BaseDaoImpl;
import imserver.service.MemberService;

@Service
@Transactional
public class MemberServiceImpl extends BaseDaoImpl<MemberInfo> implements MemberService{
	
	@Resource
	private GernateNum gernateNum;
	
	@Override
	public void register(MemberInfo memberInfo) throws DaoException {
		String memberNum = gernateNum.getMemberNum();
		memberInfo.setMemberNum(memberNum);
		super.save(memberInfo);
	}

	@Override
	public int login(String user, String pass, HttpServletRequest request) throws DaoException {
		Session session = super.getSession();
		int result = LoginStatus.LOGIN_OTHER_ERROR;
		Query query = session.createQuery("from memberInfo where memberNum=:memberNum");
		query.setParameter("memberNum", user);
		MemberInfo member = (MemberInfo)query.uniqueResult();
		if(member == null){
			result = LoginStatus.LOGIN_NOT_EXISTS;
		}else{
			if(pass.equals(member.getPass())){
				result = LoginStatus.LOGIN_SUCCESS;
				request.getSession().setAttribute("member", user);
				updateStatus(1,user);   //修改用户在线状态为在线中
			}else{
				result = LoginStatus.LOGIN_PASS_ERROR;
			}
		}
		return result;
	}

	@Override
	public boolean exists(String memberNum) throws DaoException {
		Session session = super.getSession();
		Query query = session.createQuery("from memberInfo where memberNum=:memberNum");
		query.setParameter("memberNum", memberNum);
		MemberInfo member = (MemberInfo)query.uniqueResult();
		if(member == null){
			return false;
		}else{
			return true;
		}
	}

	@Override
	public void updateStatus(int status, String memberNum) throws DaoException {
		MemberInfo memberInfo = getMember(memberNum);
		if(memberInfo != null){
			memberInfo.setOnline(status);
			super.update(memberInfo);
		}
	}

	@Override
	public MemberInfo getMember(String memberNum) throws DaoException {
		Session session = super.getSession();
		Query query = session.createQuery("from memberInfo where memberNum=:memberNum");
		query.setParameter("memberNum", memberNum);
		MemberInfo member = (MemberInfo)query.uniqueResult();
		return member;
	}

}
